#!/usr/bin/env perl
# https://github.com/shenwei356/bio_scripts

use strict;
use Getopt::Long;
use BioUtil::Util;
use BioUtil::Seq;

my $usage = q(
tab2fasta - transfrom column table to fasta fromat

Usage: $0 [options] [tablefile...]

Options:

    -l,  --linelength          Output line length
    -h,  --help                Show this help information

This script is usually used in pair with fasta2tab.
https://github.com/shenwei356/bio_scripts

);

my $para = {};
GetOptions(
    'help|h'         => \$$para{help},
    'linelength|l=i' => \$$para{linelength},
) or die $usage;

die $usage if $$para{help};

my @files = file_list_from_argv(@ARGV);

for my $file (@files) {
    my $fh = undef;

    my $is_stdin = 0;
    if ( $file eq 'STDIN' ) {
        $fh       = *STDIN;
        $is_stdin = 1;
    }
    else {
        open $fh, "<", $file
            or die "fail to open file: $file\n";
    }

    my ( $header, $seq ) = ( "", "" );
    while (<$fh>) {
        s/\r?\n//g;
        s/^\s+|\s+$//g;
        next if $_ eq ''    # blank line
            or /^#/;        # annotation

        # first column as header, and second column as sequence,
        # ignore others
        ( $header, $seq ) = split /\t/, $_;

        $header =~ s/__tab__/\t/g;

        if ( $$para{linelength} ) {
            print ">$header\n", format_seq( $seq, $$para{linelength} );
        }
        else {
            print ">$header\n$seq\n";
        }
    }

    close $fh unless $is_stdin;
}
